package com.fc.remoting.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fc.commons.JsonUtils;
import com.fc.remoting.RemotingConst;
import com.fc.remoting.exception.IRemotingException;
import com.fc.remoting.exception.IRemotingParamException;
import com.fc.remoting.logger.LogSystem;
import com.fc.remoting.logger.MonitorConfig;
import com.fc.remoting.logger.Monitorlogger;
import com.fc.remoting.logger.RemotingLogger;
import com.fc.remoting.message.Commond;
import com.fc.remoting.protocol.ProtocolAdapter;
import com.fc.remoting.protocol.ProtocolRegister;

/**
 * Servlet Request
 * 
 * @author Administrator
 *
 */
public class HttpRequestHandler {
	
	private static final String DEFAULT_ENCODE = "utf-8";
	Logger log = LoggerFactory.getLogger(HttpRequestHandler.class);
	
	
	public void Handle(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter writer = null;
		BufferedReader reader = null;
		JSONObject jObject = null;
		Object msg = null;
		try {
			reader = new BufferedReader(new InputStreamReader(request.getInputStream(), DEFAULT_ENCODE));
			StringBuilder contentMsg = new StringBuilder();
			String temp = "";
			while ((temp = reader.readLine()) != null) {
				contentMsg.append(temp);
			}
			jObject = null;
			LogSystem.instance().protocolProcessBegin(log, request);
			if (contentMsg.length() > 0) {
				jObject = JSONObject.parseObject(contentMsg.toString());
			} else {
				throw new IRemotingException("Http request content-length is empty!");
			}
			if(!jObject.containsKey(RemotingConst.MODULE) || !jObject.containsKey(RemotingConst.ORDER)){
				throw new IRemotingParamException("Param module or order does not exist");
			}
			
			int module = jObject.getIntValue(RemotingConst.MODULE);
			int order = jObject.getIntValue(RemotingConst.ORDER);
			Commond commond = Commond.valueOf(module, order);
			ProtocolAdapter protocolAdapter = ProtocolRegister.getAdapter(commond);
			msg = protocolAdapter.processHttpRequestStraight(response,jObject);
			if(msg != null){
				response.setHeader("Content-Type", "text/plain");
				response.setIntHeader("Content-Length", msg.toString().getBytes().length);
				response.setCharacterEncoding(DEFAULT_ENCODE);
				writer = response.getWriter();
				writer.write(JsonUtils.object2String(msg));
				writer.flush();
			}
			LogSystem.instance().protocolProcessComplete(log,jObject, msg,null);
//			if(msg==null || !((JSONObject)msg).get("code").equals("1")){
//				Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.handleModule, MonitorConfig.fail,null,jObject,msg);
//			}
		} catch (IOException e) {
			LogSystem.instance().protocolProcessComplete(log,null, null,e);
			RemotingLogger.getLogger().debug(e.getMessage(), e);
//			Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.handleModule, MonitorConfig.fail,e,jObject,msg);
			throw new IRemotingException(e.getMessage(), e);
		} catch (Exception e) {
			LogSystem.instance().protocolProcessComplete(log,null, null,e);
			RemotingLogger.getLogger().debug(e.getMessage(), e);
//			Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.handleModule, MonitorConfig.fail,e,jObject,msg);
			throw new IRemotingException(e.getMessage(), e);
		} finally {
		}
	}
}
